<template>
  <div class="production-plan">
     <el-button type="primary" @click="saveAll">保存主表单和明细</el-button>
    <h3 class="title">物料清单</h3>
    <!-- 基本信息 -->
     <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="物料主题">
              <el-input v-model="formData.bomSubject" placeholder="请输入主题"  />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料编号">
              <el-input v-model="formData.documentNo" placeholder="请输入编号"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="制单人员" prop="creator" required>
              <el-input v-model="formData.creator" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input v-model="formData.remarks" placeholder="请输入备注"  />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 父件信息 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="产品名称">
               <el-input 
              placeholder="请输入" 
              v-model="formData.productName" 
              required
            >
              <template #suffix>
                <el-button size="mini" @click="openAssociatedItemDialog">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
            </el-form-item>
          </el-col>
           <el-col :span="6">
            <el-form-item label="产品编码">
              <el-input v-model="formData.productCode" placeholder="请输入"  />
            </el-form-item>
          </el-col>
           <el-col :span="6">
            <el-form-item label="规格型号">
              <el-input v-model="formData.specificationModel" placeholder="请输入"  />
            </el-form-item>
          </el-col>
           <el-col :span="6">
            <el-form-item label="单位">
              <el-select v-model="formData.unit" placeholder="请选择单位">
                <el-option label="个" value="个" />
                <el-option label="顿" value="顿" />
                <el-option label="千克" value="千克" />
                <el-option label="米" value="米" />
                <el-option label="盒" value="盒" />
                <el-option label="箱" value="箱" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
              <el-form-item label="数量">
                <el-input-number v-model="formData.quantity" placeholder="请输入数量" :min="0" :step="1" />
              </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品角色">
              <el-select v-model="formData.productRole" placeholder="产品角色">
                <el-option label="自制" value="自制" />
                <el-option label="委外" value="委外" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工艺流程">
              <el-input v-model="formData.processFlow"  placeholder="请填写"  />
            </el-form-item>
          </el-col>
           <el-col :span="6">
              <el-form-item label="消耗率">
                <el-input-number v-model="formData.lossRate" placeholder="请输入" :min="0.00" :step="0.01" />
              </el-form-item>
          </el-col>
        </el-row>
          <el-form-item>
                <el-button type="primary" @click="addjihau">保存主表单</el-button>
            </el-form-item>
      </el-form>
    <!-- 物料明细明细 -->
    <div class="detail-section">
      <h4 class="sub-title">物料明细</h4>
      <el-button size="small" @click="addNewRow">新增行</el-button>
      <el-button size="small" @click="batchSaveDetails">批量保存明细</el-button>
      <el-table :data="planDetailsList" border style="width: 100%">
         <el-table-column label="产品名称" width="180px">
          <template #default="{ row }">
            <el-input 
              v-model="row.productNamess" 
              :readonly="row.isSaved"
            >
              <template #suffix>
                <el-button size="mini" @click="openProductNameDialog(row)">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="产品编号">
          <template #default="{ row }">
            <el-input v-model="row.productCodess" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格型号">
          <template #default="{ row }">
            <el-input v-model="row.specificationModelss" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template #default="{ row }">
            <el-input v-model="row.unitss" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
         <el-table-column label="比例">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.productRatio" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.quantityss" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="产品角色">
          <template #default="{ row }">
            <el-input v-model="row.productRoless" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
         <el-table-column label="产品角色">
          <template #default="{ row }">
            <el-input v-model="row.processFlowss" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.lossRatess" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="领料方式">
          <template #default="{ row }">
            <el-input v-model="row.pickupMethod" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template #default="{ row }">
            <el-input v-model="row.remarks" type="textarea" rows="3" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
          <el-button size="small" type="danger" @click="deleteDetail(row)">删除</el-button>
          <el-button size="small" type="success" @click="UpdateDetail(row)">修改</el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>

   <!-- 附件部分 -->
        <div class="attachment-section">
            <h4 class="sub-title">附件管理</h4>
            <el-button size="small" @click="batchUpload">批量上传</el-button>
            <el-table :data="attachments" border style="width: 100%">
                <el-table-column label="文件名称" prop="fileName"></el-table-column>
                <el-table-column label="文件大小" prop="fileSize"></el-table-column>
                <el-table-column label="上传人" prop="uploader"></el-table-column>
                <el-table-column label="上传时间" prop="uploadTime"></el-table-column>
            </el-table>
        </div>




         <!--物流管理产品名称选择对话框 -->
    <el-dialog
      v-model="associatedItemDialogVisible"
      width="500px"
      title="关联项目选择"
      append-to-body
    >
      <el-table
        :data="associatedItems"
        highlight-current-row
        border
        size="small"
        @current-change="handleAssociatedItemChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="productsNumber" label="产品编号" />
        <el-table-column property="productsName" label="产品名称" />
        <el-table-column property="productsNum" label="规格型号" />
        <el-table-column property="productsUnit" label="单位" />
      </el-table>
      <template #footer>
        <el-button @click="pickAssociatedItem">确定</el-button>
      </template>
    </el-dialog>

     <!-- 物理明细产品名称选择对话框 -->
    <el-dialog
      v-model="productNameDialogVisible"
      width="500px"
      title="产品名称选择"
      append-to-body
    >
      <el-table
        :data="productNames"
        highlight-current-row
        border
        size="small"
        @current-change="handleProductNameChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="productsNumber" label="产品编号" />
        <el-table-column property="productsName" label="产品名称" />
        <el-table-column property="productsNum" label="规格型号" />
        <el-table-column property="productsUnit" label="单位" />
      </el-table>
      <template #footer>
        <el-button @click="pickProductName">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

import axios from 'axios';
import { Materialread, Materialwrite } from '@/axios/axiosHelper';
const formRef = ref(null);
const currentUser = ref("admin"); 
const router = useRouter();
const route = useRoute();

// 主表单数据
const formData = reactive({
  bomid:'',
  bomSubject: "",
  documentNo: "",
  creator: currentUser.value,
  remarks: "",
  creationTime: new Date().toISOString() ,
  productName: "",
  productCode: "",
  specificationModel: "",
  unit: "",
  quantity: 0, // 数字类型
  productRole: "自制",
  processFlow: "",
  lossRate: 0.00, // 数字类型
});

// 主表单验证规则

const rules = reactive({
  bomSubject: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  documentNo: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],

});


// 明细数据列表
const planDetailsList = ref([]);

const attachments = ref([]);

// 监听路由参数变化
watch(() => route.query, async (newQuery) => {
    if (newQuery.bomid) {
        await getProductionById(newQuery.bomid);
    } else {
        // 清空表单
        formData.bomSubject = "";
        formData.documentNo = "";
        formData.creator = currentUser.value;
        formData.remarks = "";
        formData.creationTime = new Date().toISOString();
        formData.productName = "";
        formData.productCode = "";
        formData.specificationModel = "";
        formData.unit = "";
        formData.quantity = 0; // 数字类型
        formData.productRole = "自制";
        formData.processFlow = "";
        formData.bomid = null;
        planDetailsList.value = [];
    }mainData
});

const getProductionById = async (bomid) => {
    try {
        const [mainResponse, detailResponse] = await Promise.all([
        Materialread.get('/l-read/api/GetValues/FTMaterials', {
                params: { BOMID: bomid }
            }),
            Materialread.get('/l-read/api/GetValues/FTMaterialsChild', {
                params: { ChildID: bomid }
            })
        ]);

        if (mainResponse.data.code === 200) {
            const mainData = mainResponse.data.data[0];
            formData.bomSubject = mainData.bomSubject;
            formData.documentNo = mainData.documentNo;
            formData.creator = mainData.creator;
            formData.remarks = mainData.remarks;
            formData.creationTime = mainData.creationTime;
            formData.productName = mainData.productName;
            formData.productCode = mainData.productCode;
            formData.specificationModel = mainData.specificationModel;
            formData.unit = mainData.unit;
            formData.quantity = mainData.quantity;
            formData.productRole = mainData.productRole;
            formData.processFlow = mainData.processFlow;
            formData.bomid = mainData.bomid;
        }
        if (detailResponse.data.code === 200) {
            planDetailsList.value = detailResponse.data.data.map(item => ({
                childID: item.childID || '',
                productNamess: item.productNamess || "",
                productCodess: item.productCodess || "",
                specificationModelss: item.specificationModelss || "",
                unitss: item.unitss || "",
                productRatio: item.productRatio || '',
                quantityss: item.quantityss || '',
                productRoless: item.productRoless || "",
                processFlowss: item.processFlowss || "",
                lossRatess: item.lossRatess || '',
                pickupMethod: item.pickupMethod || "",
                remarks: item.remarks || "",
                bomiD11: item.bomiD11 || null,
              }));
        }
    } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('数据加载失败，请检查网络或联系管理员');
    }
};



// 保存主表单和明细
const saveAll = async () => {
  if (formRef.value) {
    const isValid = await formRef.value.validate();
    if (isValid) {
      try {
        // 保存主表单
        const response = await axios.put('https://localhost:7077/api/Ment/UpdateMaterials', formData);
        if (response.data.code === 400) {
          formData.bomid = response.data.data.bomid;
          ElMessage.success('主表单保存成功');
          router.push('/GetMaterials');
          // 保存明细
          const saveDetailPromises = planDetailsList.value.map(async (row) => {
            const detailWithId = {
              ...row,
              childID: formData.bomid
            };
            const detailResponse = await axios.put(
              'https://localhost:7077/api/Ment/AddMaterialsChild',
              detailWithId
            );
            if (detailResponse.data.code === 400) {
              row.isSaved = true;
              return true;
            } else {
              ElMessage.error(`明细保存失败：${detailResponse.data.message}`);
              return false;
            }
          });

          const results = await Promise.all(saveDetailPromises);
          if (results.every(result => result)) {
            ElMessage.success('所有明细保存成功');
            router.push('/GetMaterials');
          }
        } else {
          ElMessage.error(`主表单保存失败：${response.data.message}`);
        }
      } catch (error) {
        // console.error('保存过程中发生错误:', error.response?.data);
        // ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
      }
    }
  }
};


// // 保存主表单
// const addjihau = async () => {
//     try {
//         const response = await axios.put('https://localhost:7077/api/Ment/UpdateMaterials', formData);
//         if (response.data.code === 400) {
//             formData.bomid = response.data.data.bomid;
//             ElMessage.success('主表单保存成功');
//         } else {
//             ElMessage.error(`主表单保存失败：${response.data.message}`);
//         }
//     } catch (error) {
//         console.error('保存错误:', error);
//         ElMessage.error('保存失败，请检查网络或联系管理员');
//     }
// };
// 新增行
const addNewRow = () => {
    planDetailsList.value.push({
      childID: null,
      productNamess: "",
      productCodess: "",
      specificationModelss: "",
      unitss: "",
      productRatio:'',
      quantityss: '',
      productRoless: "",
      processFlowss: "",
      lossRatess: '',
      pickupMethod: "",
      remarks: "",
      bomid: null,
    });
};

// 批量保存明细
const batchSaveDetails = async () => {
    if (!formData.bomid) {
        ElMessage.warning('请先保存主表单');
        return;
    }

    const detailsWithId = planDetailsList.value.map(detail => ({
        ...detail,
        bomid: formData.bomid
    }));

    try {
        const response = await Materialwrite.post(
            '/l-wirth/api/Ment/PLAddMaterials',
            detailsWithId
        );
        if (response.data.code === 400) {
            // 更新 planDetailsList 中的 productionScheduleDetailId
            planDetailsList.value = response.data.data.map((item, index) => ({
                ...planDetailsList.value[index],
                childID: item.childID
            }));
            ElMessage.success('明细批量保存成功');
        } else {
            ElMessage.error(`明细批量保存失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('保存错误:', error);
        ElMessage.error('保存失败，请检查网络或联系管理员');
    }
};

// 修改单条明细
const UpdateDetail = async (row) => {
    // if (!formData.bomid) {
    //     ElMessage.warning('请先保存主表单');
    //     return;
    // }

    // const detailData = {
    //     ...row,
    //     bomid: formData.bomid
    // };

    // console.log('发送给后端的明细数据:', detailData); // 打印发送给后端的数据

    try {
        const response = await axios.put(
            'https://localhost:7077/api/Ment/UpdateMaterialsChild',
            detailData
        );
        // console.log('后端返回的响应:', response); // 打印后端返回的响应

        if (response.data.code === 400) {
            ElMessage.success('明细更新成功');
        } else {
            ElMessage.error(`更新失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('更新错误:', error);
        ElMessage.error('更新失败，请检查网络或联系管理员');
    }
};

// 删除单条记录
const deleteDetail = async (bomid) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除该条记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await Materialwrite.delete(
                `/l-wirth/api/Ment/DelMaterials`,
                {
                    params: { bomid: bomid.toString() }
                }
            );
            if (response.data.code === 300) {
                ElMessage.success('删除成功');
                ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
            } else {
                ElMessage.error(`删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除错误:', error);
            ElMessage.error('删除失败，请检查网络或联系管理员');
        }
    }
};
// 产品名称数据
const productNames = ref([]);

const productNameDialogVisible = ref(false);
const currentProductNameRow = ref(null);
const currentProductName = ref({});

// 获取产品信息
const fetchProducts = () => {
  axios.get("https://localhost:7095/api/Products/GetProducts")
    .then(res => {
      productNames.value = res.data.data;
      console.log("产品数据：", productNames.value);
      nextTick(() => {
        // 强制更新表格
      });
    })
    // .catch(error => {
    //   console.error('获取产品信息失败:', error);
    //   ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
    // });
};



// 打开产品名称选择对话框
const openProductNameDialog = (row) => {
  if (productNames.value.length === 0) {
    ElMessage.warning('产品信息正在加载，请稍后重试');
    return;
  }
  currentProductNameRow.value = row;
  productNameDialogVisible.value = true;
};

// 当前选中的产品名称行
const handleProductNameChange = (val) => {
  currentProductName.value = val;
};

// 选择产品名称
const pickProductName = () => {
  if (currentProductName.value && currentProductNameRow.value) {
    currentProductNameRow.value.productNamess = currentProductName.value.productsName;
    currentProductNameRow.value.productCodess = currentProductName.value.productsNumber;
    currentProductNameRow.value.specificationModelss = currentProductName.value.productsNum;
    currentProductNameRow.value.unitss = currentProductName.value.productsUnit;
    currentProductNameRow.value.productInfoFilled = true; // 设置标志位，表示产品信息已填充
    productNameDialogVisible.value = false;
  }
};

// 对话框显示状态
const associatedItemDialogVisible = ref(false);
const currentAssociatedItem = ref({});
// 关联项目数据
const associatedItems = ref([]);
// 打开关联项目选择对话框
const openAssociatedItemDialog = () => {
  associatedItemDialogVisible.value = true;
};
// 当前选中的关联项目行
const handleAssociatedItemChange = (val) => {
  currentAssociatedItem.value = val;
};
// 选择关联项目
const pickAssociatedItem = () => {
  if (currentAssociatedItem.value) {
    formData.productName = currentAssociatedItem.value.productsName; // 产品名称
    formData.productCode = currentAssociatedItem.value.productsNumber; // 产品编号
    formData.specificationModel = currentAssociatedItem.value.productsNum; // 规格型号
    formData.unit = currentAssociatedItem.value.productsUnit; // 单位
    associatedItemDialogVisible.value = false;
  }
};
// 获取关联项目数据
const fetchAssociatedProjects = () => {
  axios.get("https://localhost:7095/api/Products/GetProducts")
    .then(res => {
      associatedItems.value = res.data.data;

    })
    // .catch(error => {
    //   console.error('获取产品信息失败:', error);
    //   ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
    // });
};
onMounted(() => {
    if (route.query.bomid) {
        getProductionById(route.query.bomid);
    }   
  fetchProducts();

});
</script>

<style scoped>
.production-plan {
    padding: 20px;
}

.title {
    text-align: center;
    margin-bottom: 20px;
}

.sub-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: 500;
}

.detail-section,
.attachment-section {
    margin-top: 20px;
}

.el-table {
    margin-top: 10px;
}
</style>    